package cn.jsony.org.service.impl;

import cn.jsony.basic.service.impl.BaseServiceImpl;
import cn.jsony.basic.util.Md5Utils;
import cn.jsony.basic.util.StrUtils;
import cn.jsony.org.domain.Employee;
import cn.jsony.org.mapper.EmployeeMapper;
import cn.jsony.org.service.IEService;
import cn.jsony.user.domain.Logininfo;
import cn.jsony.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class EServiceImpl  extends BaseServiceImpl<Employee> implements IEService {

    @Autowired
    private LogininfoMapper logininfoMapper;


    @Autowired
    private EmployeeMapper employeeMapper;
    //操作员工和用户表的时候,要同时对loginfo进行
    @Transactional
    @Override
    public void add(Employee employee) {
        //增加和修改,对盐值和密码进行加密,为了保护信息
        String salt = StrUtils.getComplexRandomString(6);

        //获取加密之后的密码,密码加盐
        String md5 = Md5Utils.encrypByMd5(employee.getPassword() + salt);

        employee.setSalt(salt);
        employee.setPassword(md5);

        //把增加后的employee对象转换成Loginfo
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);

        employee.setLogininfo_id(logininfo.getId());
        super.add(employee);

        employeeMapper.addEmployeeRole(employee);


    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        //当前对象是管理员
        logininfo.setType(0);

        return logininfo;
    }

    @Transactional
    @Override
    public void del(Long id) {

        employeeMapper.delEmployeeRoleByEmpId(id);

        Employee employee = employeeMapper.loadById(id);
        Long logininfo_id = employee.getLogininfo_id();
        logininfoMapper.remove(logininfo_id);
        super.del(id);

    }

    @Transactional
    @Override
    public void update(Employee employee) {
        //增加和修改,对盐值和密码进行加密,为了保护信息
        String salt = StrUtils.getComplexRandomString(6);

        //获取加密之后的密码,密码加盐
        String md5 = Md5Utils.encrypByMd5(employee.getPassword() + salt);

        employee.setSalt(salt);
        employee.setPassword(md5);

        //把修改后的employee对象转换成Loginfo
        Logininfo logininfo = employee2Logininfo(employee);
        //log_infoid==Logininfo的id
        Long logininfo_id = employeeMapper.loadById(employee.getId()).getLogininfo_id();
        logininfo.setId(logininfo_id);

        logininfoMapper.update(logininfo);

        super.update(employee);


        //先删除以前的中间数据
        employeeMapper.delEmployeeRoleByEmpId(employee.getId());
        //再添加新的数据
        employeeMapper.addEmployeeRole(employee);
    }

    @Override
    public List<Employee> findByShopId(Long id) {
        return employeeMapper.findByShopId(id) ;
    }
}
